package main

import (
	"fmt"
	"io"
	"os"
	"strings"
)

func main() {
	checkSql()

	fmt.Printf("按任意键退出")
	b := make([]byte, 1)
	os.Stdin.Read(b)
}

func checkSql() {
	allFile := foreachDir(".")
	var sqlFileArray []string
	for _, file := range allFile {
		if isSqlFile(file) {
			sqlFileArray = append(sqlFileArray, file)
		}
	}
	for _, file := range sqlFileArray {
		errList := getFileErr(file)
		if len(errList) == 0 {
			fmt.Printf("√ | %s\n", file)
		}
	}
	for _, file := range sqlFileArray {
		errList := getFileErr(file)
		if len(errList) > 0 {
			errStr := strings.Join(errList, "\t|")
			fmt.Printf("X | %s\n", file)
			fmt.Println("\t" + errStr)
		}
	}
}
func getFileErr(file string) []string {
	var errList []string
	if findText(file, "set grammar") < 0 {
		errList = append(errList, "未找到'set grammar'(必须指定grammar)")
	}
	if findText(file, "channel.") > 0 {
		errList = append(errList, "发现'channel.'(禁止带库名)")
	}
	if findText(file, "cmbase.") > 0 {
		errList = append(errList, "发现'cmbase.'(禁止带库名)")
	}
	return errList
}

func isSqlFile(fileName string) bool {
	if strings.HasSuffix(fileName, ".txt") {
		return true
	}
	if strings.HasSuffix(fileName, ".sql") {
		return true
	}
	return false
}

// 遍历目录
func foreachDir(filePath string) []string {
	dirList, err1 := os.ReadDir(filePath)
	if err1 != nil {
		fmt.Println("目录读取失败")
		return nil
	}
	var fileArray []string
	for _, file := range dirList {
		filePath2 := filePath + "/" + file.Name()
		fileArray = append(fileArray, filePath2)
		if file.IsDir() {
			dirFileList := foreachDir(filePath2)
			fileArray = append(fileArray, dirFileList...)
		}
	}
	return fileArray
}

func findText(path string, text string) int {
	bytes := readAll(path)
	content := strings.ToLower(string(bytes))
	return strings.Index(content, text)
}

func readAll(path string) []byte {
	fi, err := os.Open(path)
	if err != nil {
		panic(err)
	}
	defer fi.Close()
	fd, err := io.ReadAll(fi)
	if err != nil {
		panic(err)
	}
	return fd
}
